package org.lab.mtga.core.services.impl;

import java.util.List;

import javax.inject.Inject;
import javax.persistence.EntityManager;
import javax.persistence.TypedQuery;

import org.lab.mtga.core.jpa.EntityManagerProvider;
import org.lab.mtga.core.model.Card;
import org.lab.mtga.core.services.CardRepository;
import org.lab.mtga.core.web.MagicCardCrawler;

public class DBCardRepository implements CardRepository {

	@Inject
	private EntityManagerProvider entityManagerProvider;

	@Override
	public Card findByName(String name) {
		TypedQuery<Card> query = entityManagerProvider.get().createQuery("select c from Card c where c.name = :name", Card.class);
		query.setParameter("name", name);
		List<Card> list = query.getResultList();
		if (list.isEmpty()) {
			Card card = new Card();
			card.setName(name);
			try {
				Thread.sleep(2000);
			} catch (Exception e) {
			}
			MagicCardCrawler crawler = new MagicCardCrawler(card, entityManagerProvider);
			crawler.run();
			return card;
		} else {
			return list.iterator().next();
		}
	}
}
